package com.wowoai.dialog.service.impl;

import com.wowoai.chatai.enums.ImageStatusEnum;
import com.wowoai.common.userInfo.UserInfo;
import com.wowoai.dialog.convert.DialogHistoryConvert;
import com.wowoai.dialog.entity.DialogHistoryEntity;
import com.wowoai.dialog.repository.DialogHistoryRepositoryI;
import com.wowoai.dialog.service.dto.DialogHistoryDTO;
import com.wowoai.dialog.service.enums.DialogHistoryTypeEnum;
import com.wowoai.dialog.service.DialogServiceI;
import com.wowoai.user.service.dto.UserDTO;
import com.wowoai.utils.IdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class DialogServiceImpl implements DialogServiceI {

    @Autowired
    private DialogHistoryRepositoryI dialogRepository;

    @Override
    public void saveDialogContent(UserInfo userInfo, String problem, String answer) {
        Long id = IdGeneratorUtil.nextId();
        DialogHistoryEntity dialogHistoryEntity = DialogHistoryEntity.create(id, userInfo.getUserId(),
                userInfo.getUserName(), userInfo.getPhoneNumber(), problem, answer, DialogHistoryTypeEnum.ChatGTP);
        dialogHistoryEntity.setImageState(ImageStatusEnum.CREATE_SUCCESS.getCode());//chat的先是成功
        dialogRepository.save(dialogHistoryEntity);
    }

    @Override
    @Async
    public void saveDialogContentForMidJourney(UserDTO userDTO, String taskId, String problem) {
        DialogHistoryEntity dialogHistoryEntity = DialogHistoryEntity.create(IdGeneratorUtil.nextId(), userDTO.getId(),
                userDTO.getNickName(), userDTO.getPhoneNumber(), problem,taskId,DialogHistoryTypeEnum.MIdJourney);
        dialogHistoryEntity.setImageState(ImageStatusEnum.CREATING.getCode());
        dialogRepository.save(dialogHistoryEntity);
    }

    @Override
    public DialogHistoryDTO findByTaskId(String taskId) {
        DialogHistoryEntity entity = dialogRepository.findByAnswer(taskId);
        return DialogHistoryConvert.INS.entity2DTO(entity);
    }

    @Override
    @Async
    public void changeStatus(String taskId,ImageStatusEnum imageStatusEnum) {
        DialogHistoryEntity byAnswer = dialogRepository.findByAnswer(taskId);
        if (Objects.isNull(byAnswer)){
            return;
        }
        byAnswer.setImageState(imageStatusEnum.getCode());
        dialogRepository.update(byAnswer);
    }
}
